package tk.capkiller.sharelinks.biz;

import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import javax.imageio.ImageIO;

public class ValuesInAGrid {
	private ArrayList<ArrayList<CompareImage>> grid = new ArrayList<ArrayList<CompareImage>>();

	void add(CompareImage value, int row, int col) {
		CaptchaBreaker.testWriteImage(value.getImage(),
				"C:\\temp\\smallimages\\add" + "R" + row + "C" + col + ".gif");
		resizeRow(row);
		value.setPosition(new Point(col, row));
		grid.get(row).add(value);
	}

	private void resizeRow(int row) {
		while (grid.size() - 1 < row) {
			grid.add(new ArrayList<CompareImage>());
		}
	}

	public ArrayList<CompareImage> getRow(int row) {
		return grid.get(row);
	}

	public Point getSize() {
		return new Point(grid.get(0).size(), grid.size());
	}

	public void saveAllImages(String outDir) {
		for (int r = 0; r < grid.size(); r++) {
			for (int c = 0; c < grid.get(r).size(); c++) {
				CaptchaBreaker.testWriteImage(grid.get(r).get(c).getImage(),
						outDir + "R" + r + "C" + c + ".gif");
			}

		}
	}

	public Iterator<CompareImage> iterator() {
		ArrayList<CompareImage> resultAsArrayList = new ArrayList<CompareImage>();
		for (int r = 0; r < grid.size(); r++) {
			for (int c = 0; c < grid.get(r).size(); c++) {
				resultAsArrayList.add(grid.get(r).get(c));
			}
		}
		return resultAsArrayList.iterator();
	}

	public CompareImage search(StringIntegerPair searchFor) {
		int row = GridCounter.getRowForLetter(searchFor.getStr().charAt(0));
		System.out.println("searching for '" + searchFor + "' @ Row " + row);
		int searchNumber = searchFor.getInteger();

		CompareImage imgResult = EasyImage.getImageWithThisValue(grid.get(row),
				searchNumber);
		System.out.println("found @ C" + imgResult.getPosition().x + ", R"
				+ imgResult.getPosition().y);
		return imgResult;
	}

	public void trimToSize() {
		grid.trimToSize();
		for (int c = 0; c < grid.size(); c++) {
			grid.get(c).trimToSize();
		}
	}
}
